package com.shuany.test;

import java.util.Date;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

/**
 * Lets say you have 3 servers. Server 1 and server 2 have 3GB of space and
 * server 3 has 2GB of space for cache. Here is how I would set up my client.
 * 
 */
public class MyClass {

    // create a static client as most installs only need
    // a single instance
    protected static MemCachedClient mcc = new MemCachedClient();
    // set up connection pool once at class load
    static {
        // server list and weights
        String[] servers = { "192.168.57.128:11211", "127.0.0.1:11211" };
        Integer[] weights = { 1, 1 };
        // grab an instance of our connection pool
        SockIOPool pool = SockIOPool.getInstance();
        // set the servers and the weights
        pool.setServers(servers);
        pool.setWeights(weights);
        // set some basic pool settings
        // 5 initial, 5 min, and 250 max conns
        // and set the max idle time for a conn
        // to 6 hours
        pool.setInitConn(5);
        pool.setMinConn(5);
        pool.setMaxConn(250);
        pool.setMaxIdle(1000 * 60 * 60 * 6);
        // set the sleep for the maint thread
        // it will wake up every x seconds and
        // maintain the pool size
        pool.setMaintSleep(30);
        // set some TCP settings
        // disable nagle
        // set the read timeout to 3 secs
        // and don’t set a connect timeout
        pool.setNagle(false);
        pool.setSocketTO(3000);
        pool.setSocketConnectTO(0);

        // initialize the connection pool
        pool.initialize();
        // lets set some compression on for the client
        // compress anything larger than 64k
        mcc.setCompressEnable(true);
        mcc.setCompressThreshold(64 * 1024);
        mcc.setPrimitiveAsString(true);

    }

    // from here on down, you can call any of the client calls
    public static void examples() {
       // mcc.flushAll();
        Person p = new Person("shan", "yu", 1.75, 135, 1, false);
        if (null == mcc.get("person")) {
            System.out.println("memcached not have p");
            mcc.set("person", p, new Date(10000));
        }

        Person pp = (Person) mcc.get("person");

        System.out.println(pp.getLastName() + " " + pp.getFirstName());
    }

    public static void main(String[] args) {
        MyClass.examples();
    }
}
